/***************************************************
  > Copyright (C) 2023 ==lv== All rights reserved.
  > File Name: main.c
  > Author: lv
  > Mail:joseph2009@163.com 
  > Created Time: 2023年12月09日 星期六 15时27分05秒
 ***************************************************/

#include "threadpool.h"
#include "queue.h"
#include <signal.h>
extern int run_flag;
void fun(int sig)
{
    if(sig == SIGINT)
	{
		printf("退出程序中.....\n");
		run_flag = 0;
	}
}

//生产线程
void*product_handle(void*arg)
{
	int temp = 0;
	threadPool *pool_p = (threadPool*)arg;
    while(run_flag == 1)
    {
        sem_wait(&pool_p->wsem);
        pthread_mutex_lock(&pool_p->mutex);
        //写入数据
		temp = rand()%100;
		printf("p:%d\n",temp);
		push(pool_p->que,temp);
        pthread_mutex_unlock(&pool_p->mutex);
        sem_post(&pool_p->rsem);
		usleep(100);
    }
	pthread_exit(NULL);
}
int main(int argc,const char* argv[])
{
	threadPool *pool = NULL;
	int ret = 0;
	int i = 0;
	signal(SIGINT,fun);
	pool = createThreadPool(100,10);
	//启动生产者：
	pthread_t tid = 0;
	ret = pthread_create(&tid,NULL,product_handle,(void*)pool);
	if(ret!= 0)
	{
		printf("error:%s\n",strerror(ret));
		exit(1);
	}
	pthread_join(tid,NULL);//等待生产者结束
	
	for(i = 0;i < pool->threads;i++)
	{
		sem_post(&pool->rsem);//唤醒消费者线程,读取结束标志
	}
	
	for(i = 0;i < pool->threads;i++)
	{
		pthread_join(pool->tids[i],NULL);//释放所有线程
	}
	destroyThreadPool(pool);//释放线程池资源
	return 0;
}
